package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.QueryProductListRequest;
import com.aliyun.iot20180120.models.QueryProductListResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.AliIoTConfigProperties;
import com.zzyl.service.DeviceService;
import com.zzyl.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //同步产品列表
    @Override
    public void syncProductList() {
        QueryProductListRequest request = new QueryProductListRequest();

        //请求参数
        //分页条件
        request.setPageSize(200);
        request.setCurrentPage(1);
        //公共实例
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        //调用第三方查询产品列表
        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_LIST_PRODUCT_ERROR);
        }

        //判断，如果数据为空，则中断请求
        if(!response.getBody().success){
            throw new BaseException(BasicEnum.IOT_LIST_PRODUCT_ERROR);
        }

       /* //获取数据，存储到redis
        List<ProductVo> productVoList = response.getBody().getData().getList().getProductInfo().stream().map(
                p -> BeanUtil.toBean(p, ProductVo.class)
        ).collect(Collectors.toList());
        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(productVoList));*/

        //获取数据，存储到redis
        String jsonStr = JSONUtil.toJsonStr(response.body.data.list.productInfo);
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, jsonStr);
    }

    @Override
    public List<ProductVo> getAllProduct() {

        //从redis种获取数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //如果为空，返回空集合
        if (jsonStr == null ||  jsonStr.length() == 0){
            return null;
        }
        //不为空，则返回集合
        List<ProductVo> productVos = JSONUtil.toList(jsonStr, ProductVo.class);
        return productVos;
    }



}
